<template>
  <div class="permission">
    <el-card>
      <div style="float: right">
        <el-button type="primary" @click="addClick('0', 1)">添加菜单</el-button>
      </div>
      <el-table :data="tableData" row-key="id">
        <el-table-column prop="name" label="菜单名称" />
        <el-table-column prop="code" label="权限标识" />
        <el-table-column prop="description" label="描述" />
        <el-table-column label="操作">
          <template v-slot="{ row }">
            <div>
              <el-button
                type="text"
                @click="addClick(row.id, 1)"
              >添加菜单</el-button>
              <el-button
                type="text"
                @click="addClick(row.id, 2)"
              >添加按钮</el-button>
              <el-button type="text" @click="edit(row)">编辑</el-button>
              <el-button type="text" @click="del(row.id)">删除</el-button>
            </div>
          </template>
        </el-table-column>
      </el-table>
    </el-card>
    <!-- 新增弹框组件 -->
    <!-- <Add :visible-show="addShow" @update:visibleShow="addShow = $event" /> -->
    <Add ref="add" :visible-show.sync="addShow" @getData="getData" />
  </div>
</template>

<script>
import { sysPermission, sysPermissionDelete } from '@/api/permission'
import Add from './components/Add.vue'
export default {
  components: {
    Add
  },
  data() {
    return {
      tableData: [],
      addShow: false,
      permissionShow: false
    }
  },
  created() {
    this.getData()
  },
  methods: {
    async getData() {
      const res = await sysPermission()
      this.tableData = this.changeData(res.data, '0')
    },
    // 转换树形数据
    changeData(arr, pid) {
      const newArr = arr.filter((item) => {
        if (item.pid === pid) {
          item.children = this.changeData(arr, item.id)
          return true
        }
      })
      return newArr
    },
    // 新增
    addClick(pid, type) {
      this.addShow = true
      this.$refs.add.mode = 'add'
      this.$refs.add.form.pid = pid
      this.$refs.add.form.type = type
    },
    // 删除
    del(id) {
      this.$confirm('你确认删除该条数据吗?', '提示').then(async() => {
        await sysPermissionDelete(id)
        this.$message.success('删除成功')
        this.getData()
      })
    },
    // 编辑
    edit(row) {
      this.addShow = true
      this.$refs.add.mode = 'edit'
      // 深拷贝当前行数据给form表单
      this.$refs.add.form = JSON.parse(JSON.stringify(row))
    }
  }
}
</script>

<style lang="scss" scoped>
.permission {
  padding: 20px;
}
</style>
